package xyz.ibenben.zhongdian.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.system.dao.HouseImageDao;
import xyz.ibenben.zhongdian.system.dao.RentingHouseDao;
import xyz.ibenben.zhongdian.system.entity.HouseImage;
import xyz.ibenben.zhongdian.system.entity.HouseInfo;
import xyz.ibenben.zhongdian.system.entity.RentingHouse;
import xyz.ibenben.zhongdian.system.entity.enums.HouseTypeEnum;
import xyz.ibenben.zhongdian.system.service.HouseInfoService;
import xyz.ibenben.zhongdian.system.service.RentingHouseService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 租赁房屋服务实现类
 * 提供了一些基本的服务，如获取图像等方法。
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service
public class RentingHouseServiceImpl extends ServiceImpl<RentingHouse> implements RentingHouseService {
	private final RentingHouseDao rentingHouseDao;
	private final HouseInfoService houseInfoService;
	private final HouseImageDao houseImageDao;

	@Autowired
	public RentingHouseServiceImpl(RentingHouseDao rentingHouseDao, HouseInfoService houseInfoService, HouseImageDao houseImageDao) {
		this.rentingHouseDao = rentingHouseDao;
		this.houseInfoService = houseInfoService;
		this.houseImageDao = houseImageDao;
	}

	/**
	 * save租房信息
	 * @param entity 租房的实体
	 * @param request 请求
	 * @return 是否成功的整形值
	 */
	@Transactional
	@Override
	@SystemServiceLog(description = "save租房信息")
	public int save(RentingHouse entity, HttpServletRequest request) {
		//获取房屋信息并更新
		HouseInfo info = houseInfoService.selectByKey(entity.getHouseId());
		info.setType(HouseTypeEnum.RENTING);
		houseInfoService.updateAll(info, request);
		
		return this.save(entity, request);
	}

	/**
	 * findOneWithImage租房信息
	 * @param id 房屋主键
	 * @return 租赁房屋实体
	 */
	@Override
	@SystemServiceLog(description = "findOneWithImage租房信息")
	public RentingHouse findOneWithImage(Long id) {
		RentingHouse house = rentingHouseDao.selectByPrimaryKey(id);
		HouseInfo info = houseInfoService.findOneWithImage(house.getHouseId());
		house.setInfo(info);
		//获取房屋图像信息
		Example example = new Example(HouseImage.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("houseId", id);
		List<HouseImage> list = houseImageDao.selectByExample(example);
		if(list != null && !list.isEmpty()){
			house.setList(list);
		}
		return house;
	}

	/**
	 * 根据标题获取记录
	 *
	 * @param title 标题
	 * @return 租赁信息
	 */
	@Override
	public List<RentingHouse> findByTitle(String title) {
		Example example = new Example(RentingHouse.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("title", title);
		return rentingHouseDao.selectByExample(example);
	}
}
